﻿Ext.namespace('EHSubmit.MessageBox');

//----基于从服务器端读到的数据，确定的类---------
EHSubmit.MessageBox.msgData = {
    MID : '',
    Title: '',
    Content: '',
    SenderID: '',
    ReceiverID: '',
    SenderName: '',
    ReceiverName: '',
    SendTime: '',
    RecvTime: ''
};

////////////////////////////////////////////
Ext.namespace('EHSubmit.MessageBox.Inbox');

//-----上下工具栏共用的方法---------

//-------直接点了grid的写消息--------
EHSubmit.MessageBox.Inbox.writeMsg = function writeMsg() {
    //------使收件人处显示默认信息（影响写信息处的收件人和查找到收件人后的更新操作）--------
    EHSubmit.MessageBox.msgData.SenderID = null;
    EHSubmit.MessageBox.msgData.ReceiverID = null;
    EHSubmit.MessageBox.isInbox = false;
    //----------只允许有一个写消息窗----------
    EHSubmit.showWin(EHSubmit.MessageBox.WriteMsg.window);
};

EHSubmit.MessageBox.Inbox.removeMsg = function removeMsg(button) {
    //-------对于垃圾箱需再设置删除确认功能-------
    
    var i;
    var thisGrid = button.ownerCt.ownerCt;
    var thisGridID = thisGrid.id;
    
    var msgIDSelected = new Array();
    var count = thisGrid.selModel.getCount();
    var msgSelectedList = thisGrid.selModel.getSelections();
    if (msgSelectedList) {
        for (i = 0; i < count; i++) {
            msgIDSelected[i] = msgSelectedList[i].data.ID;
        }
    }
    var msgIDSelectedList = Ext.util.JSON.encode(msgIDSelected);
    Ext.Ajax.request({
        url: EHSubmit.ajaxRoot + 'MessageHandler.ashx',
        success: function(response, opts) {
            var result = Ext.decode(response.responseText).msg;
            Ext.MessageBox.alert("提示", result);
            //-------删除成功后，要刷新一下grid----------
            thisGrid.store.reload();      
        },
        failure: function(response, opts){
            var result = Ext.decode(response.responseText).msg;
            Ext.MessageBox.alert('错误',result);
        },
        params: { Op: 'msgRemove', gridID: thisGridID, msgID: msgIDSelectedList}
    });
};

//--------------设置Checkbox及相应事件----------------
EHSubmit.MessageBox.Inbox.selModel = new Ext.grid.CheckboxSelectionModel({
    checkOnly: true,    //true if rows can only be selected by clicking on the checkbox column
    listeners: {
        // On selection change, set enabled state of the removeButton
        // which was placed into the GridPanel using the ref config
        selectionchange: function(selModel) {
            var ownerGrid = selModel.grid;
            if (selModel.getCount()) {
                ownerGrid.topRemoveButton.enable();
                ownerGrid.footRemoveButton.enable();
            } else {
                ownerGrid.topRemoveButton.disable();
                ownerGrid.footRemoveButton.disable();
            }
        }
    }
});

//---------------设置列字段-------------------------------
EHSubmit.MessageBox.Inbox.colModel = new Ext.grid.ColumnModel([
        EHSubmit.MessageBox.Inbox.selModel,
        { header: '消息ID', id: 'msgID', dataIndex: 'ID', hidden: true, hideable: false },
        { header: '发件人ID', id: 'senderID', dataIndex: 'SenderID', hidden: true, hideable: false },    //已验证宽无法按比例变化，列宽如何动态，根据最长的内容，再判断长度？？
        { header: '收件人ID', id: 'receiverID', dataIndex: 'ReceiverID', hidden: true, hideable: false },
        { header: '收件人姓名', id: 'receiverName', dataIndex: 'ReceiverName', hidden: true, hideable: false },
        { header: '发送日期', id: 'sendTime', dataIndex: 'SendTime', hidden: true, hideable: false },
        { header: '发件人姓名', id: 'senderName', dataIndex: 'SenderName', width: 150 },
        { header: '内容', id: 'content', dataIndex: 'Content', hidden: true, hideable: false },
        { header: '主题', id: 'title', dataIndex: 'Title', width: 450 },               //应该看看笔记本小屏幕下的效果
        { header: '日期', id: 'recvTime', dataIndex: 'RecvTime', width: 300, renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s') },
        { header: '接收者是否已阅', id: 'isRViewed', dataIndex: 'IsRViewed', hidden: true, hideable: false }
    ]);


    EHSubmit.MessageBox.Inbox.store = new Ext.data.Store({
        id:'inboxGridStore',
        baseParams: { Op: 'page',formType:'inbox' },      //需要传递操作参数
        proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'MessageHandler.ashx' }),  //后台具体处理

        reader: new Ext.data.JsonReader({
            isSuccess:'success',               //可作判断是否成功之用，实际中暂时未用到
            totalProperty: 'totalProperty',    //总记录个数
            root: 'root'
        }, [
            { name: 'ID' },
            { name: 'SenderID' },
            { name: 'ReceiverID'},
            { name: 'ReceiverName'},
            { name: 'SendTime'},
            { name: 'SenderName' },
            { name: 'Content'},
            { name: 'Title' },
            { name: 'RecvTime' },
            { name: 'IsRViewed'}
        ]),
        listeners:{
            //根据数据是否更改已阅的自动，刷新数据库该字段的信息
            beforeload: function(thisStore) {
                var i = 0;
                var msgIDRViewedList = new Array();
                var msgIDRViewed = null;

                var msgViewedList = thisStore.getModifiedRecords();
                //可能无修改的
                if (msgViewedList[0]) {
                    while (msgViewedList[i]) {
                        //若是作为接收者已阅
                        msgIDRViewedList[i] = msgViewedList[i].data.ID;
                        i++;
                    }

                    //--将id数组转换为json-----
                    if (msgIDRViewedList[0]) {
                        msgIDRViewed = Ext.util.JSON.encode(msgIDRViewedList);
                    }

                    Ext.Ajax.request({
                        url: EHSubmit.ajaxRoot + 'MessageHandler.ashx',
                        success: function(response, opts) {
                            //var result = Ext.decode(response.responseText).msg;
                            //Ext.MessageBox.alert("提示", result);
                            //-------删除成功后，要刷新一下grid----------
                            //thisGrid.store.reload();
                        },
                        failure: function(response, opts) {
                            var result = Ext.decode(response.responseText).msg;
                            Ext.MessageBox.alert('错误', result);
                        },
                        params: { op: 'msgViewed', msgIDRViewed: msgIDRViewed, msgIDSViewed: '[]' }
                    });
                }
                return true;
            }
        }
    });


    EHSubmit.MessageBox.Inbox.grid = {        //底部工具条的有两种选择，要确定一种*********
        xtype: 'grid',
        id: 'inboxGrid',

        store: EHSubmit.MessageBox.Inbox.store,
        cm: EHSubmit.MessageBox.Inbox.colModel,
        sm: EHSubmit.MessageBox.Inbox.selModel,
        layout: 'fit',
        loadMask: true,
        height: 410,

        frame: true,
        //autoLoad: { params: { start: 0, limit: 10} },

        //true to add css for column separation lines. Default is false.
        columnLines: true,

        // inline buttons
        //buttons: [{ text: 'Save' }, { text: 'Cancel'}],  或这样buttons也回到grid之后
        buttonAlign: 'left',


        // customize view config
        //A config object that will be applied to the grid's UI view.
        //Any of the config options available for Ext.grid.GridView can be specified here. This option is ignored if view is specified.
        viewConfig: {

            //Specify true to have the column widths re-proportioned at all times.                 
            forceFit: true,
            //        enableRowBody:true,    //用于预先显示消息内容的功能
            //isViewed: false,    //自定义的属性,判断是否已阅
            //载入数据时也根据该function来决定css
            getRowClass: function(record, rowIndex, rowParams, store) {
                //---作为收件人已阅                                                                    
                if (record.get('IsRViewed') == true) {
                    return 'x-grid3-row-viewed';
                }
            }
        },

        // inline toolbars
        tbar: [
        {
            text: '写消息',
            tooltip: '写消息',
            iconCls: 'icon-write',
            handler: EHSubmit.MessageBox.Inbox.writeMsg
        }, '-', {
            text: '删除',
            tooltip: '删除选定的项',
            iconCls: 'remove',

            // Place a reference in the GridPanel  可能相当于一个标记
            ref: '../topRemoveButton',
            disabled: true,
            handler: function(button, e) {
                EHSubmit.MessageBox.Inbox.removeMsg(button);
            }
        }
        ],

        //--------------真正页脚footbar---------------
        //     fbar: [{                   
        //         text: '按钮一',
        //         tooltip: '功能一',
        //         iconCls: 'add'
        //     }, '-', {
        //         text: '按钮二',
        //         tooltip: '功能二',
        //         iconCls: 'option'
        //     }, '-', {
        //         text: '删除',
        //         tooltip: '删除选定的项',
        //         iconCls: 'remove',

        //         // Place a reference in the GridPanel
        //         ref: '../footRemoveButton',
        //         disabled: true
        //     }],


        //--------bottombar个人理解,资料说工具栏并不意味着作为一个页脚使用---------------
        bbar: {
            id: 'inboxGridPage',
            xtype: 'paging',
            pageSize: 15,                 //只是起计算页数的作用，不影响表面,内部影响start 和 limit
            store: EHSubmit.MessageBox.Inbox.store,
            displayInfo: true,
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg: "没有记录",
            items: [
            {
                text: '写消息',
                tooltip: '写消息',
                iconCls: 'icon-write',
                handler: EHSubmit.MessageBox.Inbox.writeMsg
            }, '-', {
                //                pressed: false,
                //                enableToggle:true,
                //                text: 'Show Preview',
                //                //cls: 'x-btn-text-icon details',
                //                toggleHandler: function(btn, pressed){     //希望实现点击显示细节
                //                    var view = grid.getView();
                //                    view.showPreview = pressed;
                //                    view.refresh();
                //                }}, '-', {
                text: '删除',
                tooltip: '删除选定的项',
                iconCls: 'remove',

                // Place a reference in the GridPanel
                ref: '../footRemoveButton',
                disabled: true,
                handler: function(button, e) {
                    EHSubmit.MessageBox.Inbox.removeMsg(button);
                }
            }
            ]
        },
        listeners: {
            render: function(thisGrid) {
                //----------请求单页数据-----------------
                thisGrid.store.load({ params: { start: 0, limit: 15} });
            },
            cellclick: function(thisGrid, rowIndex, columnIndex, e) {
                if (columnIndex != 0) {                                                       //不包括check列

                    //-----变量初始化(用作判断消息来着收件箱还是发件箱)---------------
                    EHSubmit.MessageBox.isInbox = true;
                    EHSubmit.MessageBox.gridID = 'inboxGrid';
                    var store = thisGrid.getStore();
                    var record = store.getAt(rowIndex);
                    EHSubmit.MessageBox.msgData = record.data;
                    //----重新渲染-------------                                                                     
                    //var ownerTabPanel = Ext.getCmp('messageBox');
                    //ownerTabPanel.remove(thisGrid.ownerCt);          //, true);   不销毁
                    //ownerTabPanel.add(EHSubmit.MessageBox.CheckDetails.Form); windows
                    //ownerTabPanel.doLayout();  //refresh the layout

                    //若是已阅则加亮
                    if (!record.data.IsRViewed) {
                        //record.beginEdit();
                        record.set('IsRViewed', true);
                        //record.endEdit();
                        //record.commit();
                    }
                    
                    thisGrid.getView().addRowClass(rowIndex, 'x-grid3-row-viewed');

                    EHSubmit.showWin(EHSubmit.MessageBox.CheckDetails.window);
                }
            }
        }
    };



     //------收件箱-----------------
    EHSubmit.MessageBox.Inbox.form = {
        xtype: 'form',         //注意form不能嵌套！！！！！！
        id: 'inboxForm',
        title: '收件箱',
        frame: false,
        bodyStyle: 'padding:15px;',
        border: false,
        closable: true,
        items: [EHSubmit.MessageBox.Inbox.grid]
        
        //----每当激活该tab是否要刷新grid数据
//        listeners: {
//            activate: function(thisForm) {
//                thisForm.get('inboxGrid').store.reload();      
//            }
//        }
    };

